<template>
    <div class="add-role">
        <!-- 头部 -->
        <header class="add-header">
            <div class="left">
                <span class="arrow" @click="$router.back()"><i class="el-icon-arrow-left" />返回</span>

                <span>|</span>

                <span>{{ title }}</span>

            </div>

            <div class="right">
                黑马程序员
            </div>

        </header>
        <!-- 主体部分 -->
        <main class="add-main">
            <div class="step-container">
                <!-- 步骤条 -->
                <el-steps direction="vertical" :active="activeStep">
                    <el-step title="角色信息" />
                    <el-step title="权限信息" />
                    <el-step title="检查并完成" />
                </el-steps>

            </div>

            <div v-show="activeStep === 1" class="form-container">
                <!-- 第一个步骤的页面 -->
                <div class="form">
                    <el-form class="form-box" ref="roleForm" :model="roleForm" :rules="roleRules">
                        <el-form-item label="角色名称" prop="roleName">
                            <el-input v-model="roleForm.roleName" />
                        </el-form-item>

                        <el-form-item label="角色描述">
                            <el-input v-model="roleForm.remark" />
                        </el-form-item>

                    </el-form>

                </div>

            </div>

            <div v-show="activeStep === 2" class="form-container">
                <!-- 第二个步骤的页面 -->
                <div class="tree-wrapper">
                    <div v-for="item in treeList" :key="item.id" class="tree-item">
                        <div class="tree-title">{{ item.title }}</div>

                        <el-tree ref="tree" :data="item.children" show-checkbox default-expand-all node-key="id"
                            highlight-current :props="{ label: 'title' }" check-strictly />
                    </div>

                </div>

            </div>

            <div v-show="activeStep === 3" class="form-container">
                <!-- 第三个步骤的页面 -->
                <div class="title">检查并完成</div>
                <div class="form">
                    <div class="info">
                        <div class="form-item">角色名称：{{ roleForm.roleName }}</div>

                        <div class="form-item">角色描述：{{ roleForm.remark }}</div>

                        <div class="form-item">角色权限：</div>

                        <div class="tree-wrapper">
                            <div v-for="item in disableTreeList" :key="item.id" class="tree-item">
                                <div class="tree-title">{{ item.title }}</div>

                                <el-tree class="my-disabled" ref="diabledTree" :data="item.children" show-checkbox
                                    default-expand-all node-key="id" :highlight-current="false"
                                    :props="{ label: 'title' }" />
                            </div>

                        </div>

                    </div>

                </div>

            </div>

        </main>

        <footer class="add-footer">
            <div class="btn-container">
                <el-button v-if="activeStep > 1" @click="decreseStep">上一步</el-button>

                <el-button v-if="activeStep < 3" type="primary" @click="increseStep">下一步</el-button>

                <el-button v-if="activeStep === 3" type="primary" @click="confirmAdd">{{ operat }}</el-button>

            </div>

        </footer>

    </div>

</template>

<script>
import { getTreeListAPI, createRoleUserAPI, getRoleDetailAPI, updateRoleAPI } from "@/api/system";
// 处理禁用函数
export function addDisabled(treeList) {
    treeList.forEach(item => {
        item.disabled = true
        // 递归处理
        if (item.children && item.children.length > 0) {
            addDisabled(item.children)
        }
    })
}
export default {
    data() {
        return {
            activeStep: 1,// 当前激活的步骤
            roleForm: {// 角色表单数据
                roleName: '',
                remark: '',
                perms: [],// 权限列表二维数组
            },
            roleRules: {// 角色表单验证规则
                roleName: [
                    { required: true, message: '请输入角色名称', trigger: 'blur' }
                ]
            },

            treeList: [], // 权限树形列表
            disableTreeList: [], // 禁用的tree列表
        }
    },
    computed: {// 计算属性：完成页面标题的切换
        roleId() {// 获取路由参数id
            return this.$route.query.id
        },
        title() {
            return this.roleId ? '编辑角色' : '添加角色'
        },
        operat(){
            return this.roleId ? '确认修改' : '确认添加'
        }
    },
    mounted() {
        // 在初始化时候就加载好
        this.getTreeList()
        //如果url中有id，则获取角色详情
        if (this.$route.query.id) {
            // console.log('进入编辑角色')
            this.getRoleDetail()
        }
    },
    methods: {

        // 编辑角色时获取角色详情，并回填数据
        async getRoleDetail() {
            const res = await getRoleDetailAPI(this.roleId)
            const { perms, remark, roleId, roleName } = res.data
            // 回填基础表单
            this.roleForm = { perms, remark, roleId, roleName }
            // 回填Tree
            this.$refs.tree.forEach((tree, index) => {
                tree.setCheckedKeys(this.roleForm.perms[index])
            })
        },
        decreseStep() {
            if (this.activeStep === 1) return
            this.activeStep--
        },
        // 进入下一个步骤
        increseStep() {
            if (this.activeStep === 3) return
            if (this.activeStep === 1) {
                // 当前是角色信息状态，进行表单校验
                this.$refs.roleForm.validate(valid => {
                    if (valid) {
                        // 校验通过才能进入下一个状态
                        this.activeStep++
                    }
                })
            } else if (this.activeStep === 2) {

                // if(this.id){
                //     // 回填Tree
                //     this.$refs.tree.forEach((tree, index) => {
                //         tree.setCheckedKeys(this.roleForm.perms[index])
                //     })
                // }

                // 当前是权限信息状态
                this.roleForm.perms = []

                // console.log('置空后', JSON.stringify(this.roleForm.perms))
                this.$refs.tree.forEach(tree => {
                    //构造接口要求的数组格式二维数组：[[],[]]
                    const arr = tree.getCheckedKeys()// 获取选中的节点id组成的数组
                    this.roleForm.perms.push(arr)
                    // console.log(this.roleForm.perms)
                })
                // console.log('赋值后', this.roleForm.perms)
                // 如果长度为零 没有选中任何东西,flat将二维数组转换成一维数组
                if (this.roleForm.perms.flat().length === 0) {
                    this.$message({
                        type: 'error',
                        message: '请至少选择一个权限点'
                    })
                } else {
                    // 如果长度不为零，进入到检查并完成
                    this.activeStep++
                    // 回填已选择数据：勾选选项
                    this.$refs.diabledTree.forEach((tree, index) => {
                        tree.setCheckedKeys(this.roleForm.perms[index])
                    })
                    
                }
            }
        },

        // 获取功能权限列表
        async getTreeList() {
            const res = await getTreeListAPI()
            this.treeList = res.data
            //深拷贝复制树的数据
            this.disableTreeList = JSON.parse(JSON.stringify(res.data))
            // 处理禁用
            addDisabled(this.disableTreeList)
        },
        // 确认添加/修改角色
        async confirmAdd() {
            // 编辑
            if (this.roleId) {
                await updateRoleAPI(this.roleForm)
            } else {
                // 添加
                await createRoleUserAPI(
                    this.roleForm
                )
            }
            this.$message({
                type: 'success',
                message: `${this.roleId ? '编辑' : '新增'}角色成功`
            })
            this.$router.back()
        }
        
    }
}
</script>

<style scoped lang="scss">
::v-deep .el-tree-node__content label.el-checkbox.is-checked {
    span.is-checked .el-checkbox__inner {
        background-color: #0094ff;
    }
}

.my-disabled {
    color: rgba(0, 0, 0, 0.3);
}

.add-role {
    background-color: #f4f6f8;
    height: 100vh;

    .add-header {
        display: flex;
        justify-content: space-between;
        padding: 0 20px;
        height: 64px;
        line-height: 64px;
        font-size: 16px;
        font-weight: bold;
        background-color: #fff;

        .left {
            span {
                margin-right: 4px;
            }

            .arrow {
                cursor: pointer;
            }
        }

        .right {
            text-align: right;
        }
    }

    .add-main {
        position: fixed;
        top: 64px;
        bottom: 88px;
        width: 100%;
        overflow-y: auto;
        background: #f4f6f8;
        padding: 20px 230px;
        display: flex;

        .step-container {
            height: 400px;
            width: 200px;
        }

        .form-container {
            flex: 1;
            background-color: #fff;
            overflow-y: auto;

            .title {
                height: 60px;
                line-height: 60px;
                padding-left: 20px;
            }

            .form {
                margin-bottom: 20px;
                padding: 20px 65px 24px;

                .el-form {
                    display: flex;
                    flex-wrap: wrap;
                }

                .info {
                    font-size: 14px;
                    color: #666;

                    .form-item {
                        margin-bottom: 20px;
                    }
                }
            }

            .form-box {
                width: 600px;
                display: flex;
                flex-direction: column;
            }
        }
    }

    .add-footer {
        position: fixed;
        bottom: 0;
        width: 100%;
        padding: 24px 50px;
        color: #000000d9;
        font-size: 14px;
        background: #fff;
        text-align: center;
        z-index: 10001;
    }

    .tree-wrapper {
        display: flex;
        justify-content: space-between;
        flex-wrap: wrap;

        .tree-item {
            flex: 1;
            padding: 0px 4px;
            text-align: center;

            .tree-title {
                background: #f5f7fa;
                text-align: center;
                padding: 10px 0;
                margin-bottom: 12px;
            }
        }
    }
}
</style>